package com.info.zhiduoduo.admin.interceptor;

import com.info.zhiduoduo.common.utils.LogUtil;

import org.springframework.core.NamedThreadLocal;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextRootInterceptor extends HandlerInterceptorAdapter {

	//线程的时间
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
			"watch_startTime");

	@Override
	public boolean preHandle(HttpServletRequest request,
	                         HttpServletResponse response, Object handler) throws Exception {
		long beginTime = System.currentTimeMillis();// 1、开始时间
		startTimeThreadLocal.set(beginTime);// 线程绑定变量（该数据只有当前请求的线程可见）

		try {
			//action名
			String name = getMethod(handler,request);

			//请求URI
			String requestURI = request.getRequestURI();
			if(!requestURI.startsWith("/sample/test")) {
				LogUtil.info("ACTION START====================【Method : " + name + "】，【RequestURI : " + requestURI + "】====================");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		//请求参数
		//LogUtil.info("请求参数：" + charReader(request));
		return true;
	}

	/*String charReader(HttpServletRequest request) throws Exception {
		BufferedReader br = request.getReader();
		String str, wholeStr = "";
		while((str = br.readLine()) != null){
			wholeStr += str;
		}
		return wholeStr;
	}*/

	@Override
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
	                            HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		try {
			//action名
			String name = getMethod(handler,request);
			//请求URI
			String requestURI = request.getRequestURI();

			long endTime = System.currentTimeMillis();// 2、结束时间
			long beginTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量（开始时间）
			long consumeTime = endTime - beginTime;// 3、消耗的时间

			//记录操作
			//logService.saveOperateLog(0,data,name, requestURI,consumeTime, Util.getIpAddress(request));
			if(!requestURI.startsWith("/sample/test")){
				LogUtil.info("消耗的时间(毫秒):" + consumeTime);
				LogUtil.info("ACTION END====================【Method : "+name + "】，【RequestURI : " +requestURI+"】====================");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	private String getMethod(Object handler, HttpServletRequest request){
		String menthodName = "";
		if(handler instanceof HandlerMethod){
			HandlerMethod handler2 = (HandlerMethod) handler;
			menthodName = handler2.getMethod().getName();
		}else if(handler instanceof AbstractHandlerMapping){
			AbstractHandlerMapping handlerMapping =  (AbstractHandlerMapping) handler;
			menthodName  = handlerMapping.getUrlPathHelper().getServletPath(request);
		}
		return menthodName;
	}

}